﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyClients : System.Web.UI.Page
{
    List<_User_company> User_client;
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
    int UserID;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated == false)
        {
            Response.Redirect("login.aspx");
        }

        if (Request.IsAuthenticated)
        {
            string n = "";
            UserID = Convert.ToInt32(User.Identity.Name);
            SqlCommand sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            conn.Open();
            SqlDataReader dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            conn.Close();           

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData();
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }

    }

    private void SetData()
    {
        User_client = _User_company.Select_User_Clients(User.Identity.Name);
        if (User_client.Count == 0)
        {
            message_no_clients.Visible = true;
            bt_delete.Visible = false;
        }
        else
        {
            message_no_clients.Visible = false;
            Client_list.DataSource = User_client;
            Client_list.DataBind();
            bt_delete.Visible = true;
            foreach (ListViewItem item in Client_list.Items)
            {
                Label deleted = (Label)item.FindControl("statusLabel");
                if (deleted.Text == "Deleted")
                {
                    ImageButton edit = (ImageButton)item.FindControl("lnkEdit");
                    ImageButton delete = (ImageButton)item.FindControl("lnkDelete");
                    CheckBox cb = (CheckBox)item.FindControl("cb_delete_clients");
                    edit.Enabled = false;
                    delete.Enabled = false;
                    cb.Enabled = false;
                }
            }
        }
    }

    protected void Client_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Client")
        {
            var id_client = e.Item.FindControl("id_clientLabel") as Label;
            Session["Client_ID"] = id_client.Text;
        }
        if (e.CommandName == "Edit")
        {
            var id_user_client = e.Item.FindControl("id_user_clientLabel") as Label;
            var id_client = e.Item.FindControl("id_clientLabel") as Label;
            Session["User_Client_ID"] = id_user_client.Text;
            Session["Client_ID"] = id_client.Text;
            Edit_Client(id_client.Text, id_user_client.Text);            
        }
        if (e.CommandName == "Delete")
        {
            var id_client = e.Item.FindControl("id_clientLabel") as Label;
            lbl_ClientID.Text = id_client.Text;
            lbl_selected_clients.Text = "";
            Modal_Popup_Delete.Show();
        }
    }
    protected void Client_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Client_list_Page = (Client_list.FindControl("Client_list_Page")) as DataPager;
        Client_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData();
    }
    protected void Client_list_Editing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Client_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {

    }    

    //Kompāniju dzēšana POPUP
    protected void bt_delete_client_Click(object sender, EventArgs e)
    {
        if (lbl_selected_clients.Text == "True")
        {
            Select_to_delete_clients();
            foreach (string clientID in selected_clientID)
            {
                //Katrai ieķeksētajai kompānijai nomaina statusu uz DELETED
                _User_company.Delete(clientID);
                SetData();
            }
        }
        else
        {
            _User_company.Delete(lbl_ClientID.Text);
            SetData();
        }
    }
    protected void bt_delete_cancel_Click(object sender, EventArgs e)
    {
        Modal_Popup_Delete.Hide();
    }

    //Vairāku kompāniju dzēšana
    List<string> selected_clientID = new List<string>();
    protected void bt_delete_clients_Click(object sender, EventArgs e)
    {
        Select_to_delete_clients();
        if (selected_clientID.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "myalert", "alert('Select clients to delete!');", true);
        }
        else
        {
            lbl_selected_clients.Text = "True";
            Modal_Popup_Delete.Show();
        }
    }
    public void Select_to_delete_clients()
    {
        foreach (ListViewItem item in Client_list.Items)
        {
            CheckBox cb_delete_clients = (CheckBox)item.FindControl("cb_delete_clients");
            if (cb_delete_clients.Checked)
            {
                Label id_client = (Label)item.FindControl("id_clientLabel");
                string client_id = id_client.Text;
                //ieķeksētās kompānijas ID ieliek listā
                selected_clientID.Add(client_id);
            }
        }
    }

    protected void bt_add_new_client_Click(object sender, EventArgs e)
    {
        Add_Client(User.Identity.Name);
        Modal_add_client.Show();
    }
    protected void bt_cancel_Click(object sender, EventArgs e)
    {
        Modal_add_client.Hide();
    }
    
    //Klientu Pievienošana/Labošana POPUP
    #region Add/Edit Client POPUP
    public void Fill_Bank_cbo()
    {
        Drop_bank.Items.Clear();
        SqlCommand selCmd = new SqlCommand("SELECT id, bank_name FROM bank", conn);
        conn.Open();
        SqlDataReader dr = selCmd.ExecuteReader();
        while (dr.Read())
        {
            ListItem item = new ListItem();
            item.Value = dr["id"].ToString();
            item.Text = dr["bank_name"].ToString();
            Drop_bank.Items.Add(item);
        }
        Drop_bank.Items.Insert(0, "--Select--");
        dr.Close();
        conn.Close();
    }    

    public void Add_Client(string user_id)
    {
        lit_add_client.Text = "Add new client!";
        lbl_client_id.Text = "";
        lbl_user_client_id.Text = "";
        lbl_edit_client.Text = "";
        modal_message_client.Text = "&nbsp";
        modal_message_bank.Text = "&nbsp";
        modal_message_address.Text = "&nbsp";
        if (lbl_client_id.Text == "" && lbl_user_client_id.Text == "")
        {
            tb_client_name.Text = "";
            tb_client_reg_nr.Text = "";
            lbl_client_vat.Text = "";
            cb_main_client.Checked = false;
            tb_position.Text = "";
            lbl_user_id.Text = user_id;
            Bank_list.DataSource = Client_bank;
            Bank_list.DataBind();
            Address_list.DataSource = Client_address;
            Address_list.DataBind();
            Fill_Bank_cbo();
            lbl_user.Text = _User.EditUser(UserID)._Name + " " + _User.EditUser(UserID)._SecondName;
            tab_client_banks.Enabled = false;
            tab_client_address.Enabled = false;
        }
    }
    public void Edit_Client(string id_client, string id_user_client)
    {
        modal_message_client.Text = "&nbsp";
        modal_message_bank.Text = "&nbsp";
        modal_message_address.Text = "&nbsp";
        lit_add_client.Text = "Edit client!";
        tab_client_address.Enabled = true;
        tab_client_banks.Enabled = true;

        lbl_edit_client.Text = "Edit";
        lbl_client_id.Text = id_client;
        lbl_user_client_id.Text = id_user_client;
        lbl_user_id.Text = User.Identity.Name;

        lbl_user.Text = _User.EditUser(UserID)._Name + " " + _User.EditUser(UserID)._SecondName;

        lbl_user_client_id.Text = Convert.ToString(_User_company.Sel_User_company(lbl_client_id.Text)._id_user_company);
        lbl_client_id.Text = Convert.ToString(_User_company.Sel_User_company(lbl_client_id.Text)._id_company);

        tb_client_name.Text = _User_company.Sel_User_company(lbl_client_id.Text)._company_name;
        tb_client_reg_nr.Text = _User_company.Sel_User_company(lbl_client_id.Text)._company_reg_nr;
        lbl_client_vat.Text = _User_company.Sel_User_company(lbl_client_id.Text)._company_vat;

        cb_main_client.Checked = _User_company.Sel_User_company(lbl_client_id.Text)._main_company;
        tb_position.Text = _User_company.Sel_User_company(lbl_client_id.Text)._position;
        Fill_Bank_cbo();
        SetData_Address_Bank();
    }  
    
    //POPUP poga
    protected void bt_add_client_Click(object sender, EventArgs e)
    {
        string user_client = lbl_user_client_id.Text;
        string client_id = lbl_client_id.Text;
        string id_user = lbl_user_id.Text;
        string client_name = tb_client_name.Text;
        string client_reg_nr = tb_client_reg_nr.Text;
        string client_vat = "LV" + tb_client_reg_nr.Text;
        string main_client = cb_main_client.Checked.ToString();
        string position = tb_position.Text;
        string client = "true";
        string status = "Active";

        if (lbl_edit_client.Text == "Edit")
        {
            try
            {
                _User_company.Update(user_client, id_user, client_id, main_client, position, client_name, client_reg_nr, client_vat, client, status);
                if (modal_message_client.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_client.Text = "Saved!";
                    modal_message_client.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_client.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_client.Text = "Error saving data!";
                    modal_message_client.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _User_company.Insert_Company(client_name, client_reg_nr, client_vat, id_user, main_client, position, client);

                SqlCommand sCmd_MAX_user_company_id = new SqlCommand("SELECT MAX(id) FROM user_company WHERE id_user=@user_id AND client=@clientt", conn);
                sCmd_MAX_user_company_id.Parameters.Add(new SqlParameter("@user_id", System.Data.SqlDbType.Int)).Value = id_user;
                sCmd_MAX_user_company_id.Parameters.Add(new SqlParameter("@clientt", System.Data.SqlDbType.NVarChar)).Value = "true";
                conn.Open();
                lbl_user_client_id.Text = Convert.ToString(sCmd_MAX_user_company_id.ExecuteScalar());
                conn.Close();
                
                SqlCommand sCmd_MAX_comp = new SqlCommand("SELECT id_company FROM user_company WHERE id=@id AND client=@clientt", conn);
                sCmd_MAX_comp.Parameters.Add(new SqlParameter("@id", System.Data.SqlDbType.Int)).Value = lbl_user_client_id.Text;
                sCmd_MAX_comp.Parameters.Add(new SqlParameter("@clientt", System.Data.SqlDbType.NVarChar)).Value = "true";
                conn.Open();
                lbl_client_id.Text = Convert.ToString(sCmd_MAX_comp.ExecuteScalar());
                conn.Close();

                Edit_Client(lbl_client_id.Text, lbl_user_client_id.Text);

                if (modal_message_client.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_client.Text = "Saved!";
                    modal_message_client.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_client.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_client.Text = "Error saving data!";
                    modal_message_client.ForeColor = System.Drawing.Color.Red;
                }
            }
        }        
    }

    List<_Company_bank> Client_bank;
    List<_Adress> Client_address;
    public void SetData_Address_Bank()
    {
        if (lbl_client_id.Text != "")
        {
            Client_bank = _Company_bank.Select_Company_bank(lbl_client_id.Text);
            Client_address = _Adress.Select_Company_address(lbl_client_id.Text);

            if (Client_bank.Count == 0)
            {

                message_no_bank.Visible = true;
                Bank_list.DataSource = Client_bank;
                Bank_list.DataBind(); 
            }
            else
            {
                message_no_bank.Visible = false;
                lbl_account_id.Text = "";
                lbl_client_bank_id.Text = "";
                lbl_bank_id.Text = "";
                lbl_edit_bank.Text = "";
                bt_ok_bank.Text = "Add";
                tb_account.Text = "";                
                Fill_Bank_cbo();
                Bank_list.DataSource = Client_bank;
                Bank_list.DataBind();                
            }
            if (Client_address.Count == 0)
            {
                message_no_addresses.Visible = true;
                lbl_edit_address.Text = "";
                Address_list.DataSource = Client_address;
                Address_list.DataBind();
            }
            else
            {
                message_no_addresses.Visible = false;
                lbl_address_id.Text = "";
                lbl_edit_address.Text = "";
                bt_ok_address.Text = "Add";
                tb_address.Text = "";
                Address_list.DataSource = Client_address;
                Address_list.DataBind();
            }
            Modal_add_client.Show();
        }
    }

    protected void Bank_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Bank_list_Page = (Bank_list.FindControl("Bank_list_Page")) as DataPager;
        Bank_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData_Address_Bank();
    }
    protected void Bank_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            lbl_edit_bank.Text = "Edit";
            tb_account.Text = "";
            bt_ok_bank.Text = "Edit";
            modal_message_bank.Text = "";

            var client_bank_ID = e.Item.FindControl("id_client_bankLabel") as Label;
            lbl_client_bank_id.Text = client_bank_ID.Text;
            
            var bank_ID = e.Item.FindControl("id_bankLabel") as Label;
            lbl_bank_id.Text = bank_ID.Text;

            var account_ID = e.Item.FindControl("id_accountLabel") as Label;
            lbl_account_id.Text = account_ID.Text;

            try
            {
                Drop_bank.SelectedValue = _Company_bank.Select(lbl_client_bank_id.Text)._id_bank.ToString();
                tb_account.Text = _Company_bank.Select(lbl_client_bank_id.Text)._account.ToString();                
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error selecting data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        if (e.CommandName == "Delete")
        {
            try
            {
                var client_bank_ID = e.Item.FindControl("id_client_bankLabel") as Label;
                _Company_bank.Delete(client_bank_ID.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Deleted!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
                SetData_Address_Bank();
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error deleting data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    //Ķipa Bankas dzēšanas jQuery dialogboxis bet kārtīgi nestrādā(confirmValue- neattīrās) Ja izdomā kā attīrīt tad pie pogas jāpievieno: OnClick = "OnBankConfirm" OnClientClick = "Confirm()"
    public void OnBankConfirm(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {
            SetData_Address_Bank();
        }
        else if (confirmValue == "No")
        {
            SetData_Address_Bank();
        }
    }
    protected void Bank_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Bank_list_ItemDelete(object sender, ListViewDeleteEventArgs e)
    {

    }
    protected void bt_ok_bank_Click(object sender, EventArgs e)
    {
        string bank_id = Drop_bank.SelectedItem.Value;

        if (lbl_edit_bank.Text == "")
        {
            try
            {
                _Company_bank.Insert(lbl_client_id.Text, bank_id, tb_account.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Saved!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error saving data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _Company_bank.Update(lbl_client_bank_id.Text, lbl_client_id.Text, bank_id, lbl_account_id.Text, tb_account.Text);
                if (modal_message_bank.ForeColor != System.Drawing.Color.Green || modal_message_bank.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_bank.Text = "Saved!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_bank.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_bank.Text = "Error saving data!";
                    modal_message_bank.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        SetData_Address_Bank();
    }
    protected void bt_cancel_bank_Click(object sender, EventArgs e)
    {
        tb_account.Text = "";
        Fill_Bank_cbo();
        lbl_account_id.Text = "";
        lbl_client_bank_id.Text = "";
        lbl_bank_id.Text = "";
        lbl_edit_bank.Text = "";
        bt_ok_bank.Text = "Add";
        modal_message_bank.Text = "&nbsp";
        SetData_Address_Bank();
    }

    protected void Address_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager Address_list_Page = (Address_list.FindControl("Address_list_Page")) as DataPager;
        Address_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData_Address_Bank();
    }
    protected void Address_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            lbl_edit_address.Text = "Edit";
            tb_address.Text = " ";
            modal_message_address.Text = "&nbsp";
            bt_ok_address.Text = "Edit";

            var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
            int address_id = Convert.ToInt32(addres_ID.Text);
            lbl_address_id.Text = addres_ID.Text;
            try
            {
                tb_address.Text = _Adress.Select(addres_ID.Text)._address.ToString();
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error selecting data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        if (e.CommandName == "Delete")
        {
            try
            {
                var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
                _Adress.Delete(addres_ID.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Deleted!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
                SetData_Address_Bank();
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error deleting data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    //Ķipa Adreses dzēšanas jQuery dialogboxis bet kārtīgi nestrādā(confirmValue- neattīrās) Ja izdomā kā attīrīt tad pie pogas jāpievieno: OnClick = "OnAddressConfirm" OnClientClick = "Confirm()"
    public void OnAddressConfirm(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {
            foreach (ListViewItem item in Address_list.Items)
            {
                SetData_Address_Bank();
            }
        }
        else if (confirmValue == "No")
        {
            SetData_Address_Bank();
        }
       
    }
    protected void Address_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void Address_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {

    }
    protected void bt_ok_address_Click(object sender, EventArgs e)
    {
        string id_client = lbl_client_id.Text;
        string id_address = lbl_address_id.Text;

        if (lbl_edit_address.Text == "")
        {
            try
            {
                _Adress.Insert(id_client, tb_address.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Saved!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error saving data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _Adress.Update(id_address, id_client, tb_address.Text);
                if (modal_message_address.ForeColor != System.Drawing.Color.Green || modal_message_address.ForeColor == System.Drawing.Color.Green)
                {
                    modal_message_address.Text = "Saved!";
                    modal_message_address.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_address.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_address.Text = "Error saving data!";
                    modal_message_address.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        SetData_Address_Bank();
    }
    protected void bt_cancel_address_Click(object sender, EventArgs e)
    {
        tb_address.Text = "";
        lbl_address_id.Text = "";
        lbl_edit_address.Text = "";
        modal_message_address.Text = "&nbsp";
        bt_ok_address.Text = "Add";
        SetData_Address_Bank();
    }

    #endregion
}